﻿using Forum.Model.Entity;
using Forum.Model.Entity.System;
using Forum.Model.Pager;
using Forum.Model.QueryFilters;
using Forum.Repository.Extensions;
using Forum.Repository.Interface;
using Forum.Service.Interface.NoAuth;

namespace Forum.Service.Service.NoAuth
{
    public class NoticeService : INoticeService
    {
        private readonly IAppRepository<Link> _linkRepo;
        private readonly IAppRepository<Notice> _noticeRepo;
        private readonly IAppRepository<User> _userRepo;

        public NoticeService(IAppRepository<Link> linkRepo, IAppRepository<Notice> noticeRepo, IAppRepository<User> userRepo)
        {
            _linkRepo = linkRepo;
            _noticeRepo = noticeRepo;
            _userRepo = userRepo;
        }

        /// <summary>
        /// 发通知
        /// </summary>
        public void PublishNotice()
        {
            var linkNum = _linkRepo.Count(a => a.Visible);
            Notice notice = new Notice();
            notice.Msg = $"有{linkNum}条友链需要审批，请及时处理。";
            notice.PublishDate = DateTime.Now;
            notice.UserId = _userRepo.FindEntity(a => a.IsAdmin).UserId;
            _noticeRepo.Insert(notice);
        }

        /// <summary>
        /// 查询通知（分页）
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public IPagedList<Notice> GetPageList(QueryParameters param)
        {
            var querySet = _noticeRepo.SugarQueryable.Includes(a => a.User);

            // 关键词过滤
            if (!string.IsNullOrEmpty(param.Search))
            {
                querySet = querySet.Where(a => a.Msg.Contains(param.Search));
            }
            // 排序
            if (!string.IsNullOrEmpty(param.SortBy) && param.SortBy.Contains('-'))
            {
                var orderByProperty = param.SortBy.Split('-')[0];
                var ascending = param.SortBy.Split('-')[1].Contains("asc") ? " asc" : " desc";
                querySet = querySet.OrderBy(orderByProperty + ascending);
            }
            else
            {
                querySet = querySet.OrderBy(a => a.IsRead);
            }

            return querySet.ToPage(param.Page, param.PageSize);
        }

        public List<Notice> GetNoticeList()
        {
            return _noticeRepo.SugarQueryable.Where(a => !a.IsRead).Includes(a => a.User).ToList();
        }

        public Notice GetNotice(int id)
        {
            return _noticeRepo.SugarQueryable.Where(a => a.Id == id).Includes(a => a.User).First();
        }

        public bool UpdateNotice(int id)
        {
            var notice = _noticeRepo.FindEntity(a => a.Id == id);
            if (notice == null)
                return false;
            notice.IsRead = true;
            return _noticeRepo.Update(notice);
        }
    }
}
